#!/usr/bin/python
######
#       minisubscriber.py
#       Copyright Etelos Inc. 2007
#       Darien Hager
#       darien@etelos.com
######
from coordinator import *
from subscribemodule import *


class minisubscriber:
	
	__TREE_STORE = "monitor_tree.dat"
	__SUBS_STORE = "subscribed.dat"
	
	def __init__(self,rootdir):			
		self.__root = self.__sanitizeRoot(rootdir)						
	
		subdata = None;
		try:			
			handle = open(self.__root+os.sep+coordinator.SUBS_STORE,"rb")
			subdata = cPickle.load(handle)						
			handle.close()			
			return(s)
		except IOError, e:
			pass				
		except EOFError, e:
			pass

		self.__smod = subscribemodule()
		if(subdata != None):
			self.__smod.setFromPicklable(subdata)
			
	def __sanitizeRoot(self,root):
		root = os.path.realpath(root) # Take off symlinks before normpath'ing
		root = os.path.normpath(root)
		root = os.path.normcase(root)
		
		# Ensure that the __root is trailed by a slash, which will
		# vary by OS. Mac OSX / Linux it is "/", and on Windows "\"
		
		if not root.endswith(os.sep):
			root += os.sep
		
		if(not os.path.isdir(root)):
			msg = "Root directory ("+str(root)+") is invalid"
			raise IOError, msg
		return root	
		
	def tuplizePathbits(self,pb):
		temp = []
		if(type(pb) == tuple):
			temp = list(pb)			
		elif(type(pb) == str):
			temp = [pb,]
			return pb
		elif(type(pb) == list):
			temp = pb
		else:
			assert False
			
		# Stringify everything for consistency
		for i in range(0,len(temp)):
			temp[i] = str(temp[i])
		return tuple(temp)
		
	def isSubbed(self,pathbits):
		pathbits = self.tuplizePathbits(pathbits)
		return self.__smod.exists(pathbits)
